package com.jy.datapipeline.export.quartz;

import com.jy.datapipeline.common.util.BeanFactoryUtil;
import com.jy.datapipeline.export.entity.ExpTaskExecuteLogModel;
import com.jy.datapipeline.export.entity.ExpTaskModel;
import com.jy.datapipeline.export.service.ExpTaskExecuteLogService;
import com.jy.datapipeline.export.service.ExpTaskService;
import com.jy.datapipeline.common.util.CronUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JobDetailExportTaskHandler extends QuartzJobBean {
    @Autowired
    private  ExpTaskService expTaskService;
    @Autowired
    private  ExpTaskExecuteLogService expTaskExecuteLogService;

//    public JobDetailExportTaskHandler(ExpTaskService expTaskService,
//        ExpTaskExecuteLogService expTaskExecuteLogService) {
//        this.expTaskService = expTaskService;
//        this.expTaskExecuteLogService = expTaskExecuteLogService;
//    }

   
    @Override
    protected void executeInternal(JobExecutionContext context) {
        try{
            if(expTaskService==null){
                expTaskService= BeanFactoryUtil.getBean(ExpTaskService.class);
            }
            if(expTaskExecuteLogService==null){
                expTaskExecuteLogService=BeanFactoryUtil.getBean(ExpTaskExecuteLogService.class);
            }

            //获取任务的id
            JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
            String taskId = (String) jobDataMap.get("id");

            //Date nextFireTime = context.getTrigger().getNextFireTime();

           // importTaskService.startTask(taskId, nextFireTime);

//            List<Map<String,Object>> taskList= expTaskService.findExecuTask();
//            if(taskList.size()>0){
//                // log.info("task size {} "+taskList.size());
//                taskList.forEach( map ->{String taskId=map.get("task_id")==null?"":map.get("task_id").toString();
//
                    ExpTaskModel task= this.expTaskService.findByTaskId(taskId);
                    ExpTaskExecuteLogModel etelm=this.expTaskExecuteLogService.startTaskExeucte(task);
                    if(etelm!=null){
                        String netexecuteTime = CronUtils.nextExecution(task.getCrontab());
                        this.expTaskService.updateExpTaskStatus(1, taskId, netexecuteTime);
                        this.expTaskExecuteLogService.executeTask(task,etelm);
                    }
           //     });

         //   }
        }catch (Exception e){
            log.error("JobDetailExportTaskHandler error",e);
        }
    }
}
